export class ReqMgr {
    public static _ins: ReqMgr = null

    public static get ins() {
        if (this._ins == null) {
            this._ins = new ReqMgr()
        }
        return this._ins
    }

    prefix: string = 'https://carolsail.asia:3016/'

    request(url: string, method: string = 'get', data: any = null, timeout: number = 8000) {
        url = this.prefix + url
        return new Promise((resolve, reject) => {
            method = method.toLocaleLowerCase()
            const xhr = new XMLHttpRequest()
            xhr.timeout = timeout

            if (method === 'get') {
                if (data) {
                    // 形如：{fname:"carol", lname:"sail", age:18}
                    url += '?'
                    for (let key in data) {
                        url += (key + '=' + data[key] + '&')
                    }
                    url = url.substring(0, url.length - 1)
                }
                xhr.open(method, url)
                xhr.send(null)
            }

            if (method === 'post') {
                xhr.open(method, url)
                if (typeof data == 'string') {
                    // 形如："fname=carol&lname=sail&age=18"
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                } else {
                    // 形如：{fname:"carol", lname:"sail", age:25}
                    xhr.setRequestHeader('Content-Type', 'application/json')
                    data = JSON.stringify(data)
                }
                if (data) {
                    xhr.send(data)
                } else {
                    xhr.send(null)
                }
            }

            // console.log(url)

            let timer = setTimeout(() => {
                reject('请求超时了')
                throw new Error('请求超时')
            }, timeout)

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        let result = JSON.parse(xhr.responseText)
                        clearTimeout(timer)
                        resolve(result)
                    }
                }
            }

            xhr.onerror = function (err) {
                reject('请求失败,' + err)
            }
        })
    }
}


